package cn.tedu._05weibo.Controller;


import cn.tedu._05weibo.common.response.JsonResult;
import cn.tedu._05weibo.mapper.UserMapper;
import cn.tedu._05weibo.mapper.WeiboMapper;
import cn.tedu._05weibo.pojo.dto.WeiboDTO;
import cn.tedu._05weibo.pojo.entity.Weibo;
import cn.tedu._05weibo.pojo.vo.UserVO;
import cn.tedu._05weibo.pojo.vo.WeiboDetailVO;
import cn.tedu._05weibo.pojo.vo.WeiboIndexVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;


@Validated
@Api(tags = "02.微博模块")
@Slf4j
@RestController
@RequestMapping("/v1/weibo/")
public class WeiboController {

    @Autowired
    private WeiboMapper weiboMapper;
    @Autowired
    private UserMapper userMapper;

    @ApiOperation("发布微博功能")
    @PostMapping("insert")
    public JsonResult insert(@RequestBody WeiboDTO weiboDTO,@ApiIgnore HttpSession session){
        log.debug("weiboDTO="+weiboDTO);
        UserVO userVO = (UserVO) session.getAttribute("user");


        Weibo weibo = new Weibo();
        BeanUtils.copyProperties(weiboDTO, weibo);
        weibo.setCreated(new Date());
        weibo.setUserId(userVO.getId());
        weiboMapper.insert(weibo);
        return JsonResult.ok();
    }


    @ApiOperation("查询微博首页")
    @GetMapping("selectIndex")
    public JsonResult selectIndex(){
        List<WeiboIndexVO> weiboIndexVOS = weiboMapper.selectIndex();
        return JsonResult.ok(weiboIndexVOS);
    }

    //微博详情页
    @ApiOperation("微博详情页")
    @GetMapping("selectById")
    @ApiImplicitParam(name="id",value = "微博编号",required = true, dataType = "Long")
    public JsonResult selectById(@Range(min=1,max=500,message = "微博ID必须在1~500之间") @RequestParam Long id) throws IllegalAccessException {

        if(id<0){
            throw new IllegalAccessException("微博编号不能小于0");
        }
        log.debug("id="+id);
        WeiboDetailVO weiboDetailVO = weiboMapper.selectById(id);
        return JsonResult.ok(weiboDetailVO);
    }
}
